<?php
	class DB{
		private $link;
		private $tbname;
		private $field='*';
		public $result;
		private $where;
		private $order;
		private $limit;
		function __construct($tbname){
			$this->tbname=$tbname;
			$this->link=mysql_connect($GLOBALS['config']['DB_HOST'].':'.$GLOBALS['config']['DB_PORT'],$GLOBALS['config']['DB_USER'],$GLOBALS['config']['DB_PWD']) or die(mysql_error());
			mysql_query('set names '.$GLOBALS['config']['DB_CHARSET']);
			mysql_select_db($GLOBALS['config']['DB_NAME']) or die(mysql_error());
		}
		function __destruct(){
			mysql_close($this->link);
		}
		public function __call($name,$arguments){
			//注：$arguments是一个数组 $arguments=array('原参数1','原参数2',...);
			if(isset($arguments[0]))
			//$arguments[0]，得到数组参数,因为原参数仅一个，要么是空，要么是数组。
				$arguments=$arguments[0];
			if(!empty($arguments)){		
				$db=$this->$name($arguments);
			}else {
				$db=$this->$name();
			}
		//注: $db 得到方法返回的对象，然后再把对象返还给用户
			return $db;
		}
		
		private function query($sql){
			$this->result=mysql_query($sql) or die(mysql_error().'失败');
		}
		private function field($field){
			if(isset($field)){
				if(is_array($field)){
					$this->field=explode(',',$field);
				}else{
					$this->field=$field;
				}
			}
			return $this;
		}
		private function where($array){
			if(!is_array($array)){
				$this->where=' where '.$array;
			}else{
				$this->where=' where '.key_value($array,'and');
			}
			return $this;
		}
		private function order($value){
			$this->order=' order by '.$value;
			return $this;
		}
		private function limit($start,$lenght){
			$this->limit=isset($lenght)?' limit '.$start.$lenght:' limit '.$start;
			return $this;
		}
		
		//数据插入操作
		private function insert($value){
			if(!is_array($value)){
				die('sb');	
			}
			$keys=implode(',',array_keys($value));
			$value=implode(',',array_values($value));
			//为值加上引号
			$value="'".str_replace(",","','",$value)."'";
			$sql='insert into '.$this->tbname.'('.$keys.')' .' values ('.$value.')';
			$this->query($sql);
		}
		
		//更新数据库
		private function update($value){
			$value=key_value($value);
			$sql='update '.$this->tbname.' set '.$value.$this->where;
			$this->query($sql);
		}
		
		//删除字符串
		private function delete(){
			//查看是否设置了删除条件，防止删除全部数据
			if($this->where==''){
				exit;
			}
				$sql='delete from '.$this->tbname.$this->where;
				$this->query($sql);
		}
		
		private function select(){
			$sql='select '.$this->field.' from '.$this->tbname.$this->where.$this->order.$this->limit;
			$this->query($sql);
			$Allrows=array();
			while($rows=mysql_fetch_assoc($this->result)){
				$Allrows[]=$rows;
			}
			return $Allrows;
		}
		private function num_rows(){
			return mysql_num_rows($this->result);
		}
		private function find(){
			$data=$this->select();
			return $data[0];
		}
		private function assoc(){
			$Allrows=array();
			while($rows=mysql_fetch_assoc($this->result)){
				$Allrows[]=$rows;
			}
			return $Allrows;
		}
	}
?>